package com.base.project.exception;


import com.base.project.resultMapUtil.ResultCode;
import com.base.project.resultMapUtil.ResultMap;
import com.base.project.resultMapUtil.ResultMapUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.text.MessageFormat;


/**
 * @ProjectName: ExceptionAdvice
 * @Package: com.ticket.airline.ExceptionAdvice
 * @Description: 全局异常捕获
 * @Author: Z.G.C
 * @CreateDate: 2019/9/27 3:03 PM
 * @UpdateUser: Z.G.C
 * @UpdateDate: 2019/9/27 3:03 PM
 * @UpdateRemark: The modified content
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2019</p>
 */
@Slf4j
@ResponseBody
@RestControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler(Exception.class)
    public ResultMap exceptionHandler(HttpServletResponse resp, Exception exception) {
        try {
            throw exception;

        } catch (BusinessException e) {
            return ResultMapUtil.error(e.getCode(),e.getMsg());

        }catch (HttpRequestMethodNotSupportedException e) {
            String errorMsg = MessageFormat.format(ResultCode.INVALID_REQUEST_ERROR.getMsg(), e.getMethod(), e.getSupportedHttpMethods());
            return ResultMapUtil.error(ResultCode.INVALID_REQUEST_ERROR.getCode(), errorMsg);

        }catch (MissingServletRequestParameterException e) {
            System.out.println(e.getMessage());
            String errorMsg = MessageFormat.format(ResultCode.INVALID_PUBLIC_PARAM.getMsg(), e.getMessage());
            return ResultMapUtil.error(ResultCode.INVALID_PUBLIC_PARAM.getCode(), errorMsg);
        }
        catch (Exception e) {
            return ResultMapUtil.error();
        }

    }
}
